//
//  HistoryKeywordsManager.swift
//  LeTu
//
//  Created by g1 on 2024/1/14.
//

import Foundation

import Foundation
import CoreData

let kHistoryKeywordsManager = HistoryKeywordsManager.instance

class HistoryKeywordsManager: NSObject {

    static let instance = HistoryKeywordsManager()
    
    // 本地存储key
    let kHistoryKwywordsLocalKey = "HistoryKwywordsLocalKey"
    
    // 拿到AppDelegate中创建好了的NSManagedObjectContext
    lazy var context: NSManagedObjectContext = {
        let context = ((UIApplication.shared.delegate) as! AppDelegate).persistentContainer.viewContext
        
        return context
    }()
    
    // 更新数据
    private func saveContext() {
        do {
            try context.save()
        } catch {
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
    
}

// MARK: ------ 历史搜索
extension HistoryKeywordsManager {
    
    /// 保存关键词
    func saveKeyword(keyword: String) {
        
        guard keyword.count > 0 else {
            return
        }
        
        let userInfo = UserDefaults.standard
        let keywordsJsonStr = userInfo.value(forKey: kHistoryKwywordsLocalKey)
        var localKeywords = NSMutableArray(array: keywordsJsonStr == nil ? NSArray() : Utils.getArrayFromJSONString(jsonString: keywordsJsonStr as! String))
        if localKeywords.contains(keyword) {
            localKeywords.remove(keyword)
        }
        localKeywords.insert(keyword, at: 0)
        if localKeywords.count > 30 {
            localKeywords = NSMutableArray(array: Array(localKeywords.prefix(30)))
        }
        userInfo.setValue(Utils.getJSONStringFromArray(array: localKeywords), forKey: kHistoryKwywordsLocalKey)
        userInfo.synchronize()
        
    }
    
    /// 删除关键词
    func removeKeyword(keyword: String) {
        
        let userInfo = UserDefaults.standard
        let keywordsJsonStr = userInfo.value(forKey: kHistoryKwywordsLocalKey)
        let localKeywords = NSMutableArray(array: keywordsJsonStr == nil ? NSArray() : Utils.getArrayFromJSONString(jsonString: keywordsJsonStr as! String))
        if localKeywords.contains(keyword) {
            localKeywords.remove(keyword)
            userInfo.setValue(Utils.getJSONStringFromArray(array: localKeywords), forKey: kHistoryKwywordsLocalKey)
            userInfo.synchronize()
        }
        
    }
    
    /// 删除所有关键词
    func clearKeywords() {
        let userInfo = UserDefaults.standard
        userInfo.removeObject(forKey: kHistoryKwywordsLocalKey)
        userInfo.synchronize()
    }
    
    /// 获取关键词list
    func getKeywords() -> [String] {
        let userInfo = UserDefaults.standard
        let keywordsJsonStr = userInfo.value(forKey: kHistoryKwywordsLocalKey)
        guard keywordsJsonStr != nil else {
            return []
        }
        return Utils.getArrayFromJSONString(jsonString: keywordsJsonStr as! String) as! [String]
    }
    
}



